import maya.cmds as mc
import maya.mel as mel
import sys
import re
class LZ_simpleTools():
    def makeZeroGrp(self):
        sufname=mc.textFieldGrp('makeZeroGrpSuffix',q=True,text=True)
        seleobj=mc.ls(sl=True)
        for i in seleobj:
            groupname=str(i)+sufname
            mc.group(n=groupname,em=True)
            parent=mc.listRelatives(i,p=True)
            mc.parentConstraint(i,groupname,mo=False,n='needDeleteConstriant',w=1)
            mc.delete('needDeleteConstriant')
            mc.parent(i,groupname)
            if parent==None:
                pass
            else:
                mc.parent(groupname,parent)
    ####=======================================
    
    ##               ranameTools
    #--------------------------------------------------------------------------
    def addPrefixUI(self):
        prefixname=mc.textField('addPrefix',q=True,text=True)
        objsel=mc.ls(sl=True)
        print(prefixname)
        for i in objsel:
            mc.rename(i,prefixname+str(i))
    def addSufixUI(self):
        Sufixname=mc.textField('addSufix',q=True,text=True)
        objsel=mc.ls(sl=True)
        for i in objsel:
            mc.rename(i,str(i)+Sufixname)
            
    def searchReplaceNamesTool(self):
        buildOption=mc.radioButtonGrp('searchReplaceNames',q=True,sl=True)
    
        objSel=mc.ls(sl=True)
        if buildOption==1:
            mc.select(objSel,hi=True)
            objSel=mc.ls(sl=True)    
        searchname=mc.textField('Searchfor',q=True,text=True)
        replacename=mc.textField('ReplaceWith',q=True,text=True)
        print(objSel)
        for i in objSel:
            newname=str(i).replace(searchname,replacename)
            mc.rename(i,newname) 
            
    def replaceName(self):
        sufix=mc.textField('repalcename',q=True,text=True)
        selename=mc.ls(sl=True)
        splitname=selename[0].split('_')
        newname=selename[0].replace(splitname[-1],sufix)
        mc.rename(selename[1],newname)
        
    def SequenceRename(self):
        number=mc.intField('sequencerepalcename',q=True,value=True)
        numinword=[]
        selObj=mc.ls(sl=True)
        splitname=selObj[0].split('_')
        lensplitname=len(selObj)
        numWord=len(splitname[number])
        for k in range(numWord):
            try:
                result=int(splitname[number][k])
                print(result)
            except:
                result='none'
            if result!='none':
                numinword.append(k)
        lennuminword=len(numinword)
        if lennuminword==0:
            mc.error('the word selected has not a int type string')
        if lennuminword==1:
            needTrans=splitname[number][numinword[0]]
        if lennuminword>1:
            pre=numinword[0]
            suf=numinword[-1]+1
            needTrans=splitname[number][pre:suf]
        lenTrans=len(needTrans)
        if lenTrans>1:
            typenum=[]
            for j in range(lenTrans):
                splitTrans=needTrans[j]
                if int(splitTrans)!=0:
                    typenum.append(j)
            lentypenum=len(typenum)
            if lentypenum==0:
                numberTrans=0
                preNum=[]
            else:
                numberTrans=needTrans[typenum[0]]
                preNum=needTrans[:typenum[0]]
        sequence=int(numberTrans)
        
        for i in range(lensplitname-1):
            sequence=sequence+1
            oriname=selObj[0]
            replacename=preNum+str(sequence)
            sequenceStr=str(replacename)
            newname=oriname.replace(needTrans,sequenceStr)
            mc.rename(selObj[i+1],newname)
    
    def nameFieldWindow(self):
        nameFieldWindow='nameFieldWindow'
        if mc.window(nameFieldWindow,ex = True):
            mc.deleteUI(nameFieldWindow)
            
        mc.window(nameFieldWindow,widthHeight=(200, 300),t='name Field Window',menuBar = True,rtf=True,s=True)
        mc.rowColumnLayout('main',numberOfColumns=1,cal = (5,'center'),m=True)
        mc.rowColumnLayout('renameTools_01',numberOfColumns=2,cal = (5,'center'),m=True)
        selObj=mc.ls(sl=True)
        
    
        for i in selObj:
            mc.text(l=i)
            mc.nameField(o=i)
    
        mc.setParent('..')   
    
        mc.showWindow()
    ###==============================================================
    #          getSkinJnt
    #----------------------------------------------------------------
    
    def getSkinJnt(self):
        SkinObj = mc.ls(sl=True)[0]
        skinCluster=mc.listConnections(str(SkinObj)+'.inMesh',s=True)[0]
        parenconnect=mc.listConnections(skinCluster,s=True,p=True)
        worldMatriaxAll=[]
        jntskinAll=[]
        for i in parenconnect:
            if 'worldMatrix' in i:
                worldMatriaxAll.append(i)
        for k in worldMatriaxAll:
            jntname=k.split('.')[0]
            jntskinAll.append(jntname)
        mc.select(jntskinAll)
    ###=================================================================
    #         reverseSelect
    #-------------------------------------------------------------------
    def reverseSelect(self):
        objsle=mc.ls(sl=True)
        objsequence=objsle[::-1]
        mc.select(objsequence)
        currentsle=mc.ls(sl=True)
        sys.stdout.write(currentsle)
        
    ###=================================================================
    #         softor To Cluster
    #-------------------------------------------------------------------
    def softerToClu(self):

        import maya.OpenMaya as om
        
        import maya.cmds as cmds
        
        import string
        
        selection = cmds.ls(sl=True)
        
        # Strip selection of any attributes
        
        sel = string.split(selection[0], '.')
        
        richSel = om.MRichSelection()
        
        om.MGlobal.getRichSelection(richSel)
        
        richSelList = om.MSelectionList()
        
        richSel.getSelection(richSelList)
        
        path = om.MDagPath()
        
        component = om.MObject()
        
        richSelList.getDagPath(0, path, component)
        
        componentFn = om.MFnSingleIndexedComponent(component)
        
        cluster = cmds.cluster( rel=True )
        
        clusterSet = cmds.listConnections( cluster, type="objectSet" )
        
        cmds.select (selection[0], r=True)
        
        for i in range(0,componentFn.elementCount()):
        
           weight = componentFn.weight(i)
        
           v = componentFn.element(i)
        
           w = weight.influence()
        
           #print "The selection weight of vertex %d is %f." % (v, w)
        
           vtx = (sel[0]+'.vtx[%d]') % v
        
           cmds.sets(vtx, add=clusterSet[0])
        
           cmds.percent(cluster[0], vtx,  v=w )
        grp = cmds.group( cluster)
        
        cmds.select(cluster[1])
    def sphereDeriver(self,spherename='L_shoulder_dv'):
        mc.polySphere(n=spherename+'_geo')
        meshshape=mc.listRelatives(spherename+'_geo',s=True)[0]
        mc.createNode('closestPointOnMesh',n=spherename+'_cpom')
        
        meshMatrix=str(meshshape)+'.worldMatrix[0]'
        meshout=str(meshshape)+'.outMesh'
        geoshape=mc.listRelatives(spherename+'_geo',s=True)[0]
        mc.connectAttr(meshout,spherename+'_cpom.inMesh')
        
        folliclename=spherename+'_follicleshape'
        follicleparentname=spherename+'_follicle'
        mc.createNode('follicle',n=folliclename)
        follicleparent=mc.listRelatives(folliclename,p=True)[0]
        mc.rename(follicleparent,follicleparentname)
        mc.connectAttr(meshMatrix,str(folliclename)+'.inputWorldMatrix')
        mc.connectAttr(meshout,str(folliclename)+'.inputMesh')
        mc.connectAttr(str(folliclename)+'.outTranslate',follicleparentname+'.translate')
        mc.connectAttr(str(folliclename)+'.outRotate',follicleparentname+'.rotate')
        mc.setAttr(str(folliclename)+'.parameterU',0.5)
        mc.setAttr(str(folliclename)+'.parameterV',0.5)
        
        mc.select(cl=True)
        mc.spaceLocator(n=spherename+'_baseloc')
        mc.setAttr(spherename+'_baseloc.visibility',0)
        mc.parent(spherename+'_baseloc',spherename+'_geo')
        mc.select(cl=True)
        mc.spaceLocator(n=spherename+'_loc')
        mc.group(spherename+'_loc',n=spherename+'_loc_grp')
        mc.pointConstraint(spherename+'_follicle',spherename+'_loc_grp',mo=False)
        mc.aimConstraint(spherename+'_baseloc',spherename+'_loc_grp',mo=False,n='templeaim')
        mc.delete(spherename+'_follicle','templeaim')
        
        mc.select(cl=True)
        mc.spaceLocator(n=spherename+'_dvloc')
        mc.setAttr(spherename+'_dvloc.visibility',0)
        mc.parentConstraint(spherename+'_loc',spherename+'_dvloc',mo=False)
        mc.parent(spherename+'_dvloc',spherename+'_geo')
        mc.connectAttr(spherename+'_dvloc.translate',spherename+'_cpom.inPosition')
        
        
        mc.group(em=True,n=spherename+'_bridge')
        mc.addAttr(spherename+'_bridge',ln='parameter_U',h=False,k=True)
        mc.setAttr(spherename+'_bridge'+'.'+'parameter_U',k=True,cb=False)
        mc.addAttr(spherename+'_bridge',ln='parameter_V',h=False,k=True)
        mc.setAttr(spherename+'_bridge'+'.'+'parameter_V',k=True,cb=False)
        
        mc.connectAttr(str(spherename+'_cpom')+'.result.parameterU',spherename+'_bridge'+'.'+'parameter_U')
        mc.connectAttr(str(spherename+'_cpom')+'.result.parameterV',spherename+'_bridge'+'.'+'parameter_V')
          
        mc.group(spherename+'_geo',spherename+'_loc_grp',spherename+'_bridge',n=spherename+'_grp')
        
        
    #####   ---------------------------------   hide joint  ---------------------------------------
    
    
    
    